import React, { PureComponent } from 'react'

class Button extends PureComponent {
  static defaultProps = {
    throttle: 1000,
    onClick: () => {}
  }

  constructor (props) {
    super(props)
    this.locked = false
    this.onClick = this.onClickHandler.bind(this)
  }

  onClickHandler (e) {
    e.stopPropagation()
    if (this.locked) {
      return
    }
    const { throttle, onClick } = this.props
    onClick(e)
    if (throttle) {
      this.locked = true
      this.timer = setTimeout(() => { this.locked = false }, throttle)
    }
  }

  componentWillUnmount () {
    if (this.timer) {
      clearTimeout(this.timer)
    }
  }

  render () {
    const { children } = this.props
    return (
      <button
        { ...this.props}
        onClick={this.onClick}>
        {children}
      </button>
    )
  }
}

export default Button
